package com.wyz.saas.common.impl

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.annotation.DrawableRes
import androidx.annotation.NonNull
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.atom.api.ApiContext
import com.atom.api.ApiContextAware
import com.wyz.saas.api.common.FragmentApi
import java.io.IOException

abstract class AbstractButton : ApiContextAware {

    companion object {
        fun loadFragment(
            @NonNull loader: Fragment,
            @NonNull fragment: Fragment,
            addToBackStack: Boolean
        ) {
            val activity = loader.activity
            if (activity is FragmentApi) {
                activity.loadFragment(fragment, addToBackStack)
            }
        }
    }

    private lateinit var mApiImplContext: ApiContext

    override fun setApiContextAware(context: ApiContext) {
        mApiImplContext = context
    }

    fun apiContext(): ApiContext {
        return mApiImplContext
    }

    protected open fun decodeAsset(pathname: String): Bitmap? {
        val am = apiContext().appContext.assets
        try {
            am.open(pathname).use { inputStream -> return BitmapFactory.decodeStream(inputStream) }
        } catch (ex: IOException) {
        }
        return null
    }

    protected open fun decodeResource(@DrawableRes resId: Int): Bitmap? {
        return BitmapFactory.decodeResource(apiContext().appContext.resources, resId)
    }

    protected open fun getString(@StringRes resId: Int): String? {
        return apiContext().appContext.resources.getString(resId)
    }
}